package loginlog

import (
	"strings"

	Log "github.com/cihub/seelog"

	"gitee.com/tomatomeatman/golang-repository/bricks2/function/data/iputil"
	"gitee.com/tomatomeatman/golang-repository/bricks2/function/urlutil"
	"gitee.com/tomatomeatman/golang-repository/bricks2/model/msgentity"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/app"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/ginutil"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/gorm"
)

/**
 * 登录日志LoginLog表基本业务操作结构体
 */
type LoginLogService struct {
	app.ServiceBaseFunc
}

var (
	sDbName string //数据库名
)

/**
 * 初始化
 */
func init() {
	sDbName = app.ReadConfigKey("DbVariables", "BaseSystem", "base_system").(string)
	ginutil.RegisterAfter("/login/in", LoginLogService{}.AopAddLog) //当触发"LoginController.In"函数时调用LoginLogService{}.AopAddLog
}

/**
 * 验证更新数据是否存在重复 (一旦使用则覆盖通用方法)
 * @param r Http请求对象
 * @param ip 登录者IP
 * @param nameOrNo 登录者使用的用户名或工号
 * @return *msgentity.MsgEntity 返回验证结果
 */
func (service LoginLogService) AddLog(ctx ginutil.Context, nameOrNo string) *msgentity.MsgEntity {
	ip := iputil.RemoteIp(ctx.Request)
	macAddress := "" //MacAddress.getMac(ip);
	var build strings.Builder
	build.WriteString("INSERT INTO ${BaseSystem}login_log (")
	build.WriteString("name, type, user_id, user, ip, mac_address, log_date, last_call, memo,")
	build.WriteString("creator, create_date, modifieder, modified_date, state, index, edition")
	build.WriteString(") SELECT * FROM (")
	build.WriteString(" select")
	build.WriteString(" '登录日志' as name,")
	build.WriteString(" 1 as type,")
	build.WriteString(" Id as user_id,")
	build.WriteString(" ? as user,")
	build.WriteString(" ? as ip,")
	build.WriteString(" ? as mac_address,")
	build.WriteString(" NOW() as log_date,")
	build.WriteString(" NOW() as last_call,")
	build.WriteString(" null as memo,")
	build.WriteString(" '00000000' as creator,")
	build.WriteString(" NOW() as create_date,")
	build.WriteString(" '00000000' as Modifieder,")
	build.WriteString(" NOW() as modified_date,")
	build.WriteString(" 1 as state,")
	build.WriteString(" 1 as index,")
	build.WriteString(" 1 as edition")
	build.WriteString(" from ${BaseSystem}login_user")
	build.WriteString(" where id = (")
	build.WriteString(" 	select id from ${BaseSystem}login_user")
	build.WriteString(" 	where no = ?")
	build.WriteString(" 	union ")
	build.WriteString(" 	select id from ${BaseSystem}login_user")
	build.WriteString(" 	where name = ?")
	build.WriteString(" )")
	build.WriteString(" ) TMP")

	txt := build.String()
	txt = strings.Replace(txt, "${BaseSystem}", gorm.GetDbName(sDbName), -1)

	//where := map[string]interface{}{
	//	"user":       nameOrNo,
	//	"No":         nameOrNo,
	//	"Name":       nameOrNo,
	//	"ip":         ip,
	//	"macAddress": macAddress,
	//}
	//dbResult := gorm.Exec(txt, where)

	dbResult := gorm.Exec(txt, nameOrNo, ip, macAddress, nameOrNo, nameOrNo)
	if dbResult.Error != nil {
		Log.Error("新增发生异常:", dbResult.Error)
		return msgentity.Err(1002, "新增发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		Log.Error("新增失败,影响值小于1")
		return msgentity.Err(1002, "新增失败")
	}

	return msgentity.Success(8999, "新增成功")
}

/**
 * Aop方式添加日志
 * @param dateSt 开始时间范围
 * @param dateEd 结束时间范围
 * @return
 */
func (service LoginLogService) AopAddLog(ctx ginutil.Context, params ...interface{}) *msgentity.MsgEntity {
	if len(params) < 1 {
		return msgentity.Success(1000, "参数错误,但不拦截")
	}

	me := params[0].(*msgentity.MsgEntity)
	if !me.Success {
		return msgentity.Success(1001, "上层函数未正确执行结束所以不进行记录,但不拦截")
	}

	nameOrNo := urlutil.GetParam(ctx.Request, "nameOrNo", "").(string)
	if nameOrNo == "" {
		return msgentity.Success(8001, "用户名称为空") //虽然不添加,但不能影响切面
	}

	return service.AddLog(ctx, nameOrNo)
}
